﻿(function () {
    SWITCH = window.SWITCH = function (elementId) {
        return new SWITCH.fn.init(elementId);
    };
    SWITCH.fn = SWITCH.prototype = {
        init: function (elementId) {
            this.elementId = elementId;
            option.that = this;
        },

        Create: function (offValue, onValue) {
            if ((!onValue) || (typeof onValue === 'undefined') || (onValue === ''))
                onValue = 'ON';
            if ((!offValue) || (typeof offValue === 'undefined') || (offValue === ''))
                offValue = 'OFF';

            option.offValue = offValue, option.onValue = onValue;
            options.push({ 'that': option.that, 'offValue': option.offValue, 'onValue': option.onValue });

            var html =
                '<div class="flip-box">' +
                    '<div class="flip-box-handle"></div><span class="flip-box-label">' + offValue + '</span>' +
                        '</div>';

            var switchControl = $('<div id="' + option.that.elementId + '-Switch"></div>');
            switchControl.addClass("flip-box-container");
            switchControl.html(html);

            var txtElement = $('#' + option.that.elementId);
            txtElement.hide();
            txtElement[0].parentNode.insertBefore(switchControl[0], txtElement[0]);

            option.that.Toggle(txtElement.val());

            $('.flip-box', switchControl).unbind('click').bind('click', function () {
                option = {};
                var currentElementId = this.parentNode.id.replace('-Switch', '');
                $(options).each(function (index, opt) {
                    if (opt.that.elementId === currentElementId) {
                        option = opt;
                    }
                    if (option) return;
                });

                option.that.Toggle(txtElement.val() === onValue ? offValue : onValue);
            });
        },
        Toggle: function (value) {
            var context = $('#' + option.that.elementId + '-Switch');
            if (value === option.onValue) {
                $('div.flip-box-handle', context).css("float", "right");
                $('span.flip-box-label', context).css("float", "left");
                $('span.flip-box-label', context).text(option.onValue);
            } else {
                $('div.flip-box-handle', context).css("float", "left");
                $('span.flip-box-label', context).css("float", "right");
                $('span.flip-box-label', context).text(option.offValue);
            }

            document.getElementById(option.that.elementId).value = value === '' ? option.offValue : value;
        }
    };

    var option = {};
    var options = [];

    SWITCH.fn.init.prototype = SWITCH.fn;
})();